package com.tianci.appstore.ui.list;

import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Typeface;
import android.graphics.drawable.Drawable;
import android.text.TextUtils.TruncateAt;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.ScaleAnimation;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.ImageView.ScaleType;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.coocaa.x.framework.app.CoocaaApplication;
import com.coocaa.x.framework.utils.LogUtils;
import com.coocaa.x.framework.utils.NativeImageCache;
import com.coocaa.x.framework.utils.NativeImageCache.SmartBitmap;
import com.coocaa.x.service.XServiceManager;
import com.coocaa.x.service.litepm.data.AppInfo;
import com.skyworth.logsdk.appstore.LogAPIForAppStore;
import com.tianci.appstore.AppListActivity;
import com.tianci.appstore.AppListActivity.ListActivityType;
import com.tianci.appstore.R;
import com.tianci.appstore.ui.SkinManager;
import com.tianci.appstore.ui.data.APKData;
import com.tianci.appstore.ui.data.SkyAppBaseData;
import com.tianci.appstore.ui.data.SkyListAppData;
import com.tianci.appstore.ui.data.SkyListAppData.ListType;
import com.tianci.appstore.ui.list.SkyListAdapter.OnItemClickListener;
import com.tianci.appstore.ui.list.SkyListAdapter.SelectableListener;
import com.tianci.appstore.ui.util.UICommon;
import com.tianci.appstore.ui.widget.CatchImageView;
import com.tianci.appstore.ui.widget.SkyBaseItemView;
import com.tianci.appstore.ui.widget.StrokeTextView;
import com.tianci.appstore.utils.AsyncTask;
import com.tianci.appstore.utils.SkyConstants;
import com.tianci.appstore.utils.SkyNetImageCache;

import java.io.File;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

/**
 * 列表页中的app块View 使用此view的列表有：1.我的应用列表、2.卸载应用列表、3.清理缓存列表、4.应用转移列表
 * 其中1的supportMultiSel为false，而234的为true
 **/
public class ListBlock extends SkyBaseItemView {
    protected ListType listType;
    protected static int titleSize = SkyConstants.Dpi(35);
    protected static int infoTextSize = SkyConstants.Dpi(25);
    protected static int statusTextSize = SkyConstants.Dpi(28);
    protected ImageView iconImage;
    protected LinearLayout rightLayout;
    protected TextView infoText;
    protected ImageView cornerImage;
    protected ImageView tickImage;

    protected Drawable tickDrawable;
    protected Drawable unTickDrawable;

    protected SkyListAppData data;
    protected boolean inSelectionMode = false;
    protected boolean multiSelected = false;

    protected MuitlSelectionListener multiSelectListener;
    protected OnItemClickListener clickListener;
    protected SelectableListener selectableListener;
    protected static int iconTopMargin = SkyConstants.Div(41);
    protected static int iconLeftMargin = SkyConstants.Div(30);
    private SmartBitmap mIcon = null;
    protected Bitmap cornerBitmap;
    private TextView cornerView = null;
    private static final String CORNER_CONFIG = "corner_config";
    private static final String CLICKED = "clicked";

    public ListBlock(Context context, ListType type) {
        super(context);
        this.listType = type;
        // TODO Auto-generated constructor stub
        // createView();
    }

    @Override
    protected void createView() {
        // TODO Auto-generated method stub
        iconImage = new CatchImageView(mContext);
        iconImage.setScaleType(ScaleType.CENTER_CROP);
        LayoutParams iconParams = new LayoutParams(iconWidth, iconWidth);
        iconParams.leftMargin = iconLeftMargin;
        iconParams.topMargin = iconTopMargin;
        this.addView(iconImage, iconParams);

        rightLayout = new LinearLayout(mContext);
        rightLayout.setOrientation(LinearLayout.VERTICAL);
        rightLayout.setGravity(Gravity.LEFT | Gravity.TOP);
        LayoutParams rightParams = new LayoutParams(LayoutParams.MATCH_PARENT, iconWidth);
        rightParams.setMargins(SkyConstants.Div(192), iconTopMargin, SkyConstants.Div(20), 0);
        this.addView(rightLayout, rightParams);

        titleText = new StrokeTextView(mContext);
        ((StrokeTextView) titleText).setMainColor(Color.WHITE);
        ((StrokeTextView) titleText).setStrokeColor(Color.parseColor("#945e00"));
        ((StrokeTextView) titleText).setM_bDrawSideLine(false);
        titleText.setSelected(false);
        titleText.setTextSize(titleSize);
        SkinManager.setTextColor(titleText, R.color.titleColor);
        rightLayout.addView(titleText, new LayoutParams(LayoutParams.MATCH_PARENT,
                LayoutParams.WRAP_CONTENT));

        infoText = UICommon.newTextView(mContext, infoTextSize, R.color.appInfoColor);
        infoText.setEllipsize(TruncateAt.END);
        rightLayout.addView(infoText, new LayoutParams(LayoutParams.MATCH_PARENT,
                LayoutParams.WRAP_CONTENT));
    }

    @Override
    protected void onDraw(Canvas canvas) {
        try {
            super.onDraw(canvas);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    private void addCorner() {
        if (data.updateBean != null && data.updateBean.isSubscript) {
            LogUtils.i("corner",data.getTitle() + " the corner type " + data.updateBean.subscriptType +
                    " prop " + data.updateBean.subscriptProp + " time " + data.updateBean.createSubTime);
            SharedPreferences preferences = mContext.getSharedPreferences(CORNER_CONFIG,0);
            String cornerData = preferences.getString(data.getPkgName(),"");
            LogUtils.i("corner","data " + cornerData);
            if (!cornerData.contains(data.updateBean.createSubTime))
                cornerData = "";
            if (!cornerData.equals("")){
                String[] temp = cornerData.split("\\|");
                LogUtils.d("corner","temp0 " + temp[0] + " temp2 " + temp[2]);
                if (temp[0].equals("0")){
                    if (!cornerData.contains(CLICKED)){
                        refreshCornerView();
                    }else
                        hideCornerView();
                }else{
                    SimpleDateFormat sdf =   new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    try {
                        Date date = sdf.parse(temp[2]);
                        if (temp[0].equals("1")){
                            if (System.currentTimeMillis() - date.getTime() > SkyConstants.THREE_DAY){
                                hideCornerView();
                            }else
                                refreshCornerView();
                        }else if(temp[0].equals("2")){
                            if (System.currentTimeMillis() - date.getTime() > SkyConstants.WEEK){
                                hideCornerView();
                            }else
                                refreshCornerView();
                        }
                    } catch (ParseException e) {
                        e.printStackTrace();
                    }
                }
            }else{
                refreshCornerView();
                SharedPreferences.Editor editor = preferences.edit();
                SimpleDateFormat sdf =   new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                editor.putString(data.getPkgName(),
                        data.updateBean.subscriptProp + "|" + data.updateBean.createSubTime
                                + "|" + sdf.format(new Date()));
                editor.commit();
            }
        } else {
            hideCornerView();
        }
    }

    private void hideCornerView(){
        if (cornerView != null) {
            cornerView.clearAnimation();
            cornerView.setVisibility(View.GONE);
        }
    }

    private void refreshCornerView(){
        if (cornerView == null) {
            cornerView = new TextView(mContext);
            cornerView.setGravity(Gravity.CENTER);
            cornerView.getPaint().setFakeBoldText(true);
            cornerView.setLineSpacing(CoocaaApplication.Div(4), 0.8f);
            cornerView.setTextColor(getResources().getColor(android.R.color.white));
            cornerView.setTextSize(CoocaaApplication.Dpi(26));
            addView(cornerView);
        }
        if (data.updateBean.subscriptType == 0) {
            FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(
                    ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
            params.leftMargin = CoocaaApplication.Div(196);
            params.topMargin = CoocaaApplication.Div(117);
            cornerView.setLayoutParams(params);
            cornerView.setText("");
            cornerView.setTextSize(0);
            cornerView.setBackgroundResource(SkyConstants.getIconId(String.valueOf(data.updateBean.subscriptType)));
            ScaleAnimation animation =new ScaleAnimation(1.0f, 1.4f, 1.0f, 1.4f,
                    Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f);
            animation.setDuration(1250);
            animation.setRepeatCount(-1);
            animation.setRepeatMode(Animation.REVERSE);
            cornerView.startAnimation(animation);
        } else {
            FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(
                    ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT,
                    Gravity.BOTTOM | Gravity.RIGHT);
            cornerView.setMinHeight(CoocaaApplication.Div(45));
            cornerView.setTextSize(CoocaaApplication.Dpi(26));
            cornerView.setBackgroundResource(SkyConstants.getIconId(String.valueOf(data.updateBean.subscriptType)));
            String txt = data.updateBean.subscriptText;
            if (txt == null)
                txt = "";
            if (txt.length() > 2) {
                txt = txt.substring(0, 2) + "\n" + txt.substring(2, txt.length());
            }
            cornerView.setText(txt);
            cornerView.setLayoutParams(params);
        }
        cornerView.setVisibility(View.VISIBLE);
        setPadding(SkyConstants.shadowWidth, SkyConstants.shadowWidth,
                SkyConstants.shadowWidth, SkyConstants.shadowWidth - CoocaaApplication.Div(2));
    }


    @Override
    public void update(final SkyAppBaseData data) {
        // TODO Auto-generated method stub
        this.data = (SkyListAppData) data;
        addCorner();
        long startTime = Calendar.getInstance().getTimeInMillis();
        LogUtils.d("logo", "----------------------updating listBlock");
        // 多选模式时，有多页数据情况：翻页后，再翻回来时需要刷新是否被选中的状态
        if (inSelectionMode) {
            this.multiSelected = false;
            String pkgName = "";
            for (SkyListAppData selData : multiSelectListener.getSelectedDataList()) {
                pkgName = ((SkyListAppData) data).getPkgName();
                if (pkgName == null)
                    break;
                if (pkgName.equals(selData.getPkgName())) {
                    this.multiSelected = true;
                    break;
                }
            }
            refreshSelectState();
        }

        final String pkgName = ((SkyListAppData) data).getPkgName();
        if (data instanceof APKData) {

        } else if (data.getIconUrl() != null && !data.getIconUrl().equals("")) {
            LogUtils.d("logo", "update  11111:" + data.getTitle() + " " + data.getIconUrl());
            if (!SkyNetImageCache.getSkyNetImageCache().downloadAppListLogo(pkgName,
                    data.getIconUrl(), this, iconWidth, iconWidth, SkyConstants.Div(25)))
                iconImage.setImageDrawable(SkinManager.getResDrawable(R.drawable.icon_default));
        } else if (pkgName != null && !pkgName.equals("")) {
            iconImage.setImageDrawable(SkinManager.getResDrawable(R.drawable.icon_default));
            AsyncTask.runOnThread(new Runnable() {

                @Override
                public void run() {
                    // TODO Auto-generated method stub
                    if (!SkyNetImageCache.getSkyNetImageCache().getLogoByPkg(pkgName,
                            ListBlock.this, iconWidth, iconWidth, SkyConstants.Div(25))) {
                        mIcon = NativeImageCache.getInstance().getBitmapByPkg(mContext, pkgName,
                                ListBlock.this.data.getMainActivity(), iconWidth, iconWidth, SkyConstants.Div(25));
                        if (mIcon != null) {
                            ListBlock.this.loadFinished(pkgName, mIcon.get());
                        }
                    }
                }
            });
        }

        UICommon.setText(titleText, data.getTitle());
        String showInfo = this.data.getShowInfo();
        UICommon.setText(infoText, showInfo, true);
        if (showInfo == null || showInfo.trim().length() == 0)
            rightLayout.setGravity(Gravity.LEFT | Gravity.CENTER_VERTICAL);
        LogUtils.d("logo", "    set title and showInfo finished");

        String cornerUrl = this.data.getExtra();
        if (cornerUrl != null && cornerUrl.trim().length() > 0) {
            if (cornerImage == null) {
                cornerImage = new CatchImageView(mContext);
                cornerImage.setScaleType(ScaleType.FIT_END);
            }
            if (cornerImage.getParent() == null) {
                LayoutParams cornerParams = new LayoutParams(SkyConstants.cornerIconWidth,
                        SkyConstants.cornerIconWidth);
                int gap = (SkyConstants.cornerIconWidth - SkyConstants.iconWidth) / 2;
                cornerParams.leftMargin = iconLeftMargin - gap;
                cornerParams.topMargin = iconTopMargin - gap;
                this.addView(cornerImage, cornerParams);
            }
            cornerImage.setImageBitmap(null);

            SkyNetImageCache.getSkyNetImageCache().downloadUrl("", cornerUrl, this, iconWidth,
                    iconWidth);
        } else {
            if (cornerImage != null && cornerImage.getParent() != null)
                cornerImage.setVisibility(View.INVISIBLE);
        }
        long endTime = Calendar.getInstance().getTimeInMillis();
        LogUtils.d("logo", "    Total update finished, duration = " + (endTime - startTime)
                + "!!!!!!!!!!!!!!");
    }

    public void updateShowInfo(String str) {
        UICommon.setText(infoText, str, true);
    }

    private void initTickImage() {
        if (tickDrawable == null)
            tickDrawable = SkinManager.getResDrawable(R.drawable.ticked);
        if (unTickDrawable == null)
            unTickDrawable = SkinManager.getResDrawable(R.drawable.tick_not);
        if (tickImage == null) {
            tickImage = new ImageView(mContext);
        }
        if (tickImage.getParent() == null)
            this.addView(tickImage, new LayoutParams(LayoutParams.WRAP_CONTENT,
                    LayoutParams.WRAP_CONTENT, Gravity.RIGHT | Gravity.BOTTOM));
        tickImage.setVisibility(View.INVISIBLE);
    }

    @Override
    protected void refreshImage(String url, Bitmap result) {
        // TODO Auto-generated method stub
        if (result == null || result.isRecycled()) {
            return;
        }
        // if(result == null)
        // LogUtils.d("my_logo",
        // "title = "+data.getTitle()+", pkgName = "+data.getPkgName()+", iconUrl = "+data.getIconUrl()
        // +", bitmap == null!!!!!!!!!!!");
        // else
        // LogUtils.d("my_logo",
        // "title = "+data.getTitle()+", pkgName = "+data.getPkgName()+", iconUrl = "+data.getIconUrl()
        // +", bitmap != null");
        // LogUtils.d("my_logo", "   callback url = "+url);
        if (data == null)
            return;
        if (data.getIconUrl() != null && !data.getIconUrl().equals("")
                && url.equals(data.getIconUrl())) {
            iconImage.setImageBitmap(result);

        } else if (data.getPkgName() != null && !data.getPkgName().equals("")
                && url.equals(data.getPkgName())) {
            iconImage.setImageBitmap(result);

        } else if (data.getExtra() != null && !data.getExtra().equals("")
                && url.equals(data.getExtra())) {
            LogUtils.d("extra", "data title = " + data.getTitle() + ", extra = " + data.getExtra());
            if (cornerImage != null) {
                cornerImage.setImageBitmap(result);
                cornerImage.setVisibility(View.VISIBLE);
            }
        }
    }

    public void setSelectMode(boolean selMode) {
        inSelectionMode = selMode;
    }

    // 是否开启多选模式
    public void refreshSelectState() {
        if (inSelectionMode) {
            initTickImage();
            if (multiSelected)
                tickImage.setImageDrawable(tickDrawable);
            else
                tickImage.setImageDrawable(unTickDrawable);

            tickImage.setVisibility(View.VISIBLE);
        } else {
            if (tickImage != null)
                tickImage.setVisibility(View.INVISIBLE);
            multiSelected = false;
        }
    }

    //
    // public void refreshIsMultiSelected(boolean multiSelected)
    // {
    // if(data == null)
    // return;
    // this.multiSelected = multiSelected;
    // }

    // 多选模式时，用户点击之后要反转选中状态
    protected void toggleMultiSelected() {
        if (data == null)
            return;
        this.multiSelected = !multiSelected;
        // refreshIsMultiSelected(multiSelected);
        if (multiSelectListener != null) {
            if (multiSelectListener.onMultiSelectChanged(data, multiSelected)) {
                refreshSelectState();
            }
        } else {
            refreshSelectState();
        }
    }

    public boolean getIsMultiSelected() {
        if (data == null)
            return false;
        return multiSelected;
    }

    public String getDataId() {
        if (data == null)
            return null;
        return data.getId();
    }

    public SkyAppBaseData getData() {
        return data;
    }

    public String getPkgName() {
        if (data == null)
            return null;
        return data.getPkgName();
    }

    @Override
    public void onClick(View v) {
        if (data == null)
            return;
        if (inSelectionMode) {
            if (selectableListener == null || selectableListener.checkSelectable(data, this.mIndex))
                toggleMultiSelected();
        } else {
            switch (listType) {
                case LOCAL_APP_LIST:
                    if (this.data.getId().equals("more")) {
                        AppListActivity.type = ListActivityType.MORE_LIST;
                        Intent intent = new Intent(mContext, AppListActivity.class);
                        intent.putExtra("listType", ListType.LOCAL_APP_LIST.toString());
                        mContext.startActivity(intent);
                    } else {
                        AsyncTask.runOnThread(new Runnable() {
                            @Override
                            public void run() {
                                // TODO Auto-generated method stub
                                AppInfo info = new AppInfo();
                                info.pkgName = data.getPkgName();
                                info.mainActivity = data.getMainActivity();
                                try {
                                    LogUtils.d("start appinfo " + info.pkgName + "/"
                                            + info.mainActivity);
                                    XServiceManager.getLitePMService().startAppByComponentName(mContext.getClass().getName(), false,
                                            new ComponentName(info.pkgName, info.mainActivity));
                                    // ServiceFacotry.getAppService().startApp(info);
                                    if (isChildrenMode) {
                                        LogUtils.d("log", "isChildrenMode  pkg:" + info.pkgName);
                                        LogAPIForAppStore.AUIClickCount(info.pkgName, info.appName);
                                    }
                                    LogUtils.d("end start appinfo " + info.pkgName + "/"
                                            + info.mainActivity);
                                    if (data.updateBean != null && data.updateBean.subscriptProp == 0){
                                        SharedPreferences preferences = mContext.getSharedPreferences(CORNER_CONFIG, 0);
                                        String cornerData = preferences.getString(data.getPkgName(),"");
                                        if (!cornerData.contains(CLICKED)){
                                            SharedPreferences.Editor editor = preferences.edit();
                                            editor.putString(data.getPkgName(),
                                                    preferences.getString(data.getPkgName(),"") + "|" +CLICKED);
                                            editor.commit();
                                            AsyncTask.runOnUiThread(new Runnable() {
                                                @Override
                                                public void run() {
                                                    hideCornerView();
                                                }
                                            });
                                        }
                                    }
                                } catch (Exception e) {
                                    LogUtils.d(e.getMessage());
                                    e.printStackTrace();
                                }
                            }
                        });
                    }
                    break;
                case UNINSTALL_APP_LIST:
                case CLEAR_CACHE_LIST:
                case MOVE_APP_LIST:
                case LAUNCH_ON_BOOT_LIST:
                case SELECTED_LAUNCH_LIST:
                    if (clickListener != null)
                        clickListener.onBlockClicked(this, data, this.mIndex);
                    break;
            }
        }
    }

    public void clearData() {
        this.data = null;
        iconImage.setImageBitmap(null);
        titleText.setText("");
        infoText.setText("");
        this.multiSelected = false;
        if (cornerImage != null)
            cornerImage.setVisibility(View.INVISIBLE);
        if (inSelectionMode) {
            if (tickImage == null)
                initTickImage();
            tickImage.setImageDrawable(unTickDrawable);
        }
    }

    @Override
    public void setChildrenMode(boolean childrenMode) {
        // TODO Auto-generated method stub
        super.setChildrenMode(childrenMode);
        if (titleText != null && titleText instanceof StrokeTextView) {
            ((StrokeTextView) titleText).setMainColor(Color.WHITE);
            ((StrokeTextView) titleText).setStrokeColor(Color.parseColor("#945e00"));
            ((StrokeTextView) titleText).setM_bDrawSideLine(false);
        }
    }

    private static Typeface typeface = null;

    @Override
    public void onFocusChange(View arg0, boolean hasFocus) {
        // TODO Auto-generated method stub
        if (isChildrenMode) {
            this.setPadding(SkyConstants.shadowChildWidth, SkyConstants.shadowChildWidth,
                    SkyConstants.shadowChildWidth, SkyConstants.shadowChildWidth);
            if (titleText instanceof StrokeTextView)
                ((StrokeTextView) titleText).setM_bDrawSideLine(hasFocus);
            if (hasFocus) {
                if (typeface == null) {
                    String path = "/system/fonts/child.ttf";
                    File file = new File(path);
                    if (file.exists())
                        typeface = Typeface.createFromFile(file);
                    else
                        typeface = Typeface.DEFAULT;
                }
                titleText.setTypeface(typeface);
                titleText.setTextSize(SkyConstants.Dpi(42));
            } else {
                titleText.setTextSize(SkyConstants.Dpi(35));
                titleText.setTextColor(Color.WHITE);
                titleText.setTypeface(Typeface.DEFAULT);
            }
            if (titleText != null) {
                titleText.setSelected(hasFocus);
            }
            this.selected = hasFocus;
        } else {
            if (titleText instanceof StrokeTextView)
                ((StrokeTextView) titleText).setM_bDrawSideLine(false);
            super.onFocusChange(arg0, hasFocus);
        }
    }

    public void setMultiSelectListener(MuitlSelectionListener multiSelectListener) {
        this.multiSelectListener = multiSelectListener;
    }

    public interface MuitlSelectionListener {
        public boolean onMultiSelectChanged(SkyListAppData data, boolean selected);

        public List<SkyListAppData> getSelectedDataList();

        public void setSelectedDataList(List<SkyListAppData> selList);
    }

    public void setClickListener(OnItemClickListener listener) {
        this.clickListener = listener;
    }

    public void setSelectableListener(SelectableListener listener) {
        this.selectableListener = listener;
    }

    @Override
    public void destory() {
        iconImage.setImageBitmap(null);
        if (cornerImage != null) {
            cornerImage.setImageBitmap(null);
        }
        if (mIcon != null) {
            mIcon.recycle();
        }


        if (cornerBitmap != null && !cornerBitmap.isRecycled()) {
            cornerBitmap.recycle();
            cornerBitmap = null;
        }
    }
}
